import { keepAlive } from "@plasmohq/persistent/background"

keepAlive()

const workUrl =
  "https://market.m.taobao.com/app/alsc-medicine/huatuo/index.html"

function alarmContent() {
  const url =
    "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f00f3eaf-2d98-418b-9bb3-424b07dfd755"
  fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      msgtype: "markdown",
      markdown: {
        content:
          "饿了么异常告警\n> 三方渠道:<font color='comment'> 饿了么</font>\n>> 当前未找到实时监控页面<font color='warning'> 请检查 </font>"
      }
    })
  })
}

function refreshTask(shouldCheck = false) {
  // 检测是否存在 workUrl 开头的 tab
  chrome.tabs.query({ url: workUrl + "*" }, (tabs) => {
    if (tabs.length === 0) {
      if (shouldCheck) {
        alarmContent()
      }
      // 如果没有找到 workUrl 开头的 tab，则打开一个新的 tab 并告警
      chrome.tabs.create({ url: workUrl }, (tab) => {
        if (chrome.runtime.lastError) {
          console.error("Failed to create tab:", chrome.runtime.lastError)
        } else {
          console.warn(
            "No tab found for workUrl. Created a new tab with ID:",
            tab.id
          )
        }
      })
    } else {
      // 如果找到了 workUrl 开头的 tab，则刷新该 tab
      tabs.forEach((tab) => {
        chrome.tabs.reload(tab.id, {}, () => {
          if (chrome.runtime.lastError) {
            console.error("Failed to reload tab:", chrome.runtime.lastError)
          } else {
            console.info("Tab with ID", tab.id, "has been refreshed.")
          }
        })
      })
    }
  })
}

// 初始化时执行一次
refreshTask()

// 设置定时器 每 2 分钟执行一次
chrome.alarms.create("elm-monitor-alarm", { periodInMinutes: 2 })

// 监听定时器触发事件
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm && alarm.name == "elm-monitor-alarm") {
    console.info(`${new Date()} alarm triggered:`, alarm.name)
    refreshTask(true)
  }
})
